package com.enation.app.shop.front.api.appcontroller;

import com.enation.app.base.core.service.IMemberManager;
import com.enation.app.shop.core.goods.model.Goods;
import com.enation.app.shop.core.goods.service.IGoodsManager;
import com.enation.app.shop.core.member.model.MemberComment;
import com.enation.app.shop.core.member.service.IMemberCommentManager;
import com.enation.app.shop.core.member.service.IMemberOrderItemManager;
import com.enation.app.shop.core.order.model.Order;
import com.enation.app.shop.core.order.model.OrderItem;
import com.enation.app.shop.core.order.plugin.cart.CartPluginBundle;
import com.enation.app.shop.core.order.service.ICartManager;
import com.enation.app.shop.core.order.service.IOrderFlowManager;
import com.enation.app.shop.core.order.service.IOrderManager;
import com.enation.app.shop.front.api.commentagain.entity.CommentAgain;
import com.enation.app.shop.front.api.commentagain.service.ICommentAgainManager;
import com.enation.app.shop.front.api.commentlike.entity.CommentLike;
import com.enation.app.shop.front.api.commentlike.service.ICommentLikeManager;
import com.enation.eop.SystemSetting;
import com.enation.eop.sdk.context.EopSetting;
import com.enation.eop.sdk.utils.StaticResourcesUtil;
import com.enation.framework.action.JsonResult;
import com.enation.framework.util.DateUtil;
import com.enation.framework.util.FileUtil;
import com.enation.framework.util.JsonResultUtil;
import com.enation.framework.util.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;

/**
 * 评论的类
 */
@Scope("prototype")
@Controller
@RequestMapping("/app/comment")
public class CommentAppController{

    @Autowired
    private IMemberCommentManager memberCommentManager;
    @Autowired
    private IGoodsManager goodsManager;
    @Autowired
    private ICartManager cartManager;
    @Autowired
    private CartPluginBundle cartPluginBundle;
    @Autowired
    private IOrderFlowManager orderFlowManager;
    @Autowired
    private IMemberOrderItemManager memberOrderItemManager;
    @Autowired
    private ICommentLikeManager commentLikeManager;
    @Autowired
    private ICommentAgainManager commentAgainManager;
    @Autowired
    private IOrderManager orderManager;
    @Autowired
    private IMemberManager memberManager;


    /**
     *    //获取一个商品的评论列表,包括评论数
     * @param userid
     * @param goodsid
     * @param grade
     * @return
     */
    @ResponseBody
    @RequestMapping("/getcommentbygoods")
    public JsonResult getCommentByproductionid(Integer userid,Integer goodsid,Integer grade){
        if (grade==null){
            List<Map<String,Object>>  colist= memberCommentManager.getGoodsComments(goodsid,1);
            if (colist==null){
                return JsonResultUtil.getErrorJson("该商品还没有评论");
            }
            List<Map<String,Object>> newco=new ArrayList<Map<String, Object>>();
            for (Map<String,Object> comment:colist){
                Map<String,Object> map=new HashMap<String, Object>();
                Integer commentid=Integer.valueOf(comment.get("comment_id").toString());
                //Integer commentid1=Integer.parseInt(comment.get("comment_id").toString());
                map.put("commentid",commentid);
                map.put("uname",comment.get("uname"));
                int uid=Integer.valueOf(comment.get("member_id").toString());
                List<Order> order=orderManager.getByUserIdAndStatus(uid,null);
                try {
                    for (Order order1:order){
//                        List<OrderItem> itemList =orderManager.listGoodsItems(order1.getOrder_id());
//                        for (OrderItem orderItem:itemList){
//                            if (goodsid==orderItem.getGoods_id()){
//                                Long buytime=order1.getOrdertime();
//                                map.put("buytime",buytime);
//                            }
//                        }
                        Long buytime=order1.getOrdertime();
                        map.put("buytime",buytime);
                    }
                }catch (Exception e){

                }
                String grade1=comment.get("grade").toString();
                map.put("commentstar",comment.get("star"));
                try {
                    map.put("face", StaticResourcesUtil.transformPathapp(comment.get("face").toString()));
                }catch (Exception e){
                    System.out.println("没有图片");
                }
                Long i=Long.valueOf(comment.get("dateline").toString());
                map.put("commentdate",i*1000);
                map.put("content",comment.get("content"));
                List<Map<String, Object>> imglist=memberCommentManager.getCommentGalleryImg(commentid);
                List<String> commentimg=new ArrayList<String>();
                if (imglist==null){
                    map.put("img",new ArrayList<String>());
                }else {
                    for (Map<String,Object> map2:imglist){
                        String value=map2.get("original").toString();
                        commentimg.add(StaticResourcesUtil.transformPathapp(value));
                    }
                    map.put("img",commentimg);
                }
                Goods goods=goodsManager.getGoods(goodsid);
                map.put("goodsname",goods.getName());
                Integer commentagain= commentAgainManager.getCount(commentid);
                Integer like= commentLikeManager.count(commentid);
                CommentLike commentLike=commentLikeManager.getByUseridAndCommentId(userid,commentid,goodsid);
                if (commentLike==null){
                    map.put("thisuserlike",false);
                }else {
                    if (commentLike.getStatus()==2){
                        map.put("thisuserlike",false);
                    }else {
                        map.put("thisuserlike",true);
                    }
                }
                map.put("like",like);
                map.put("commentagain",commentagain);
                newco.add(map);
            }
            Map<String,Object> map1=new HashMap<String,Object>();
            int count1=memberCommentManager.getCommentsGradeCount(goodsid,1);
            int count2=memberCommentManager.getCommentsGradeCount(goodsid,2);
            int count3=memberCommentManager.getCommentsGradeCount(goodsid,3);//好评数量
            int count=memberCommentManager.getCommentsCount(goodsid);
            if (count == 0) {
                map1.put("sup", "100%");
            } else {
                DecimalFormat df = new DecimalFormat("0%");
                float ab = (float) count3 / count;
                map1.put("sup", df.format(ab));
            }
            map1.put("badcomment",count1);
            map1.put("middlecomment",count2);
            map1.put("goodcomment",count3);
            map1.put("totalcomment",count);
            Map map2=new HashMap();
            map2.put("commentlist",newco);
            map2.put("countmap",map1);
            return JsonResultUtil.getObjectMessageJson(map2,"获取一个商品的评论列表,包括评论数");
        }else {
            List<Map<String,Object>>  colist= memberCommentManager.getGoodsComments(goodsid,1,grade);
            List<Map<String,Object>> newco=new ArrayList<Map<String, Object>>();
            for (Map<String,Object> comment:colist){
                Map<String,Object> map=new HashMap<String, Object>();
                Integer commentid=Integer.valueOf(comment.get("comment_id").toString());
                map.put("commentid",commentid);
                map.put("uname",comment.get("uname"));
                map.put("face",StaticResourcesUtil.transformPathapp(comment.get("face").toString()));
                Long i=Long.valueOf(comment.get("dateline").toString());
                map.put("commentdate",i*1000);
                map.put("content",comment.get("content"));
                String grade1=comment.get("grade").toString();
                map.put("commentstar",comment.get("star"));
                CommentLike commentLike=commentLikeManager.getByUseridAndCommentId(userid,commentid,goodsid);
                if (commentLike==null){
                    map.put("thisuserlike",false);
                }else {
                    if (commentLike.getStatus()==2){
                        map.put("thisuserlike",false);
                    }else {
                        map.put("thisuserlike",true);
                    }
                }
                int uid=Integer.valueOf(comment.get("member_id").toString());
                List<Order> order=orderManager.getByUserIdAndStatus(uid,null);
                try {
                    for (Order order1:order){
//                        List<OrderItem> itemList =orderManager.listGoodsItems(order1.getOrder_id());
//                        for (OrderItem orderItem:itemList){
//                            if (goodsid==orderItem.getGoods_id()){
//                                Long buytime=order1.getOrdertime();
//                                map.put("buytime",buytime);
//                            }
//                        }
                        Long buytime=order1.getOrdertime();
                        map.put("buytime",buytime);
                    }
                }catch (Exception e){

                }
                List<Map<String, Object>> imglist=memberCommentManager.getCommentGalleryImg(commentid);
                List<String> commentimg=new ArrayList<String>();
                if (imglist==null){
                    map.put("img",new ArrayList<String>());
                }else {
                    for (Map<String,Object> map2:imglist){
                        String value=map2.get("original").toString();
                        commentimg.add(StaticResourcesUtil.transformPathapp(value));
                    }
                    map.put("img",commentimg);
                }
                Goods goods=goodsManager.getGoods(goodsid);
                map.put("goodsname",goods.getName());
                Integer commentagain= commentAgainManager.getCount(commentid);
                Integer like= commentLikeManager.count(commentid);
                map.put("like",like);
                map.put("commentagain",commentagain);
                newco.add(map);
            }
            return JsonResultUtil.getObjectMessageJson(newco,"通过评分获取评价列表");
        }
    }

    /**
     * 发表评论
     *
     * @param goods_id:商品id,int型，必填项
     //* @param commenttype:评论类型，int型，必填项，可选值：1或2，1为评论，2为咨询。
     * @param content:评论内容，String型，必填项。
    // * @param file:评论的图片，File类型，可选项。
     * @param grade
     *            :评分
     * @return 返回json串 result 为1表示添加成功，0表示失败 ，int型 message 为提示信息
     *///grade  1差评 2中评 3好评
    @ResponseBody
    @RequestMapping(value = "/creatcomment", produces = MediaType.APPLICATION_JSON_VALUE)
    @Transactional
    public JsonResult add(Integer goods_id,
                           String content,
                           Integer grade,
                           Integer userid,
                           Integer star,
                           HttpServletRequest request) {
        MemberComment memberComment = new MemberComment();
        int type = 1; // StringUtil.toInt(request.getParameter("commenttype"),0);
        // 判断是不是评论或咨询
        if (type != 1 && type != 2) {
            //StringUtil
            return JsonResultUtil.getErrorJson("系统参数错误！");
        }
        memberComment.setType(type);

        // int goods_id = StringUtil.toInt(request.getParameter("goods_id"),0);
        if (goodsManager.get(goods_id) == null) {
            return JsonResultUtil.getErrorJson("此商品不存在！");
        }
        memberComment.setGoods_id(goods_id);

        // String content = request.getParameter("content");
        if (StringUtil.isEmpty(content)) {
            return JsonResultUtil.getErrorJson("评论或咨询内容不能为空！");
        } else if (content.length() > 1000) {
            return JsonResultUtil.getErrorJson("请输入1000以内的内容！");
        }
        memberComment.setContent(content);
        memberComment.setMember_id(userid == null ? 0 : userid);
        memberComment.setDateline(System.currentTimeMillis() / 1000);
        //memberComment.setDateline(System.currentTimeMillis());
        memberComment.setGrade(grade);
        memberComment.setStar(star);
        try {
            memberCommentManager.add(memberComment);
            int commentid=memberComment.getComment_id();
            List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
            for (MultipartFile multipartFile:files){
                String fileName=multipartFile.getOriginalFilename();
                if(!FileUtil.isAllowUpImg(fileName)){
                    throw new IllegalArgumentException("不被允许的上传文件类型");
                }
                String ext = FileUtil.getFileExt(fileName);
                fileName = DateUtil.toString(new Date(), "mmss") + StringUtil.getRandStr(4) + "." + ext;
                String static_server_path= SystemSetting.getStatic_server_path();
                String filePath =  static_server_path + "/attachment/";
                String subFolder="comment";
                if(subFolder!=null){
                    filePath+=subFolder +"/";
                }
                String timePath=this.getTimePath();
                String path  = EopSetting.FILE_STORE_PREFIX+ "/attachment/" +(subFolder==null?"":subFolder)+"/"+timePath+"/"+fileName;
                filePath +=timePath;
                filePath += fileName;
                try {
                    FileUtil.write(multipartFile.getInputStream(),filePath);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String commentimg=path;
                int i=1;
                memberCommentManager.creategallery(commentid,commentimg);
            }
            return JsonResultUtil.getSuccessJson("发表成功");
        } catch (RuntimeException e) {
            Logger logger = Logger.getLogger(getClass());
            logger.error("发表评论出错", e);
            return JsonResultUtil.getErrorJson("发表评论出错" + e.getMessage());
        }
    }

    /**
     * //去评价列表
     * @param orderid
     * @param userid
     * @return
     */
    @ResponseBody
    @RequestMapping("/getCommentDetail")
    public JsonResult getCommentDatail(Integer orderid,Integer userid){
      List<Order> orders=orderManager.getByUserIdAndStatus(userid,null);
      if (orders==null){
          return JsonResultUtil.getErrorJson("您还没有订单信息");
      }
        List<OrderItem> list=orderManager.listGoodsItems(orderid);
        List list1=new ArrayList();
        for (OrderItem orderItem:list){
            Map map1=new HashMap();
            map1.put("goodsimg",StaticResourcesUtil.transformPathapp(orderItem.getImage()));
            map1.put("goodsname",orderItem.getName());
            map1.put("goodsid",orderItem.getGoods_id());
            list1.add(map1);
        }
        return JsonResultUtil.getObjectMessageJson(list1,"去评价列表");
    }

    /**
     *   //给评论点赞-取消点赞
     * @param userid
     * @param commentid
     * @return
     */
    @ResponseBody
    @RequestMapping("/likeComment")
    public JsonResult likeComment(Integer userid,Integer commentid){
        Integer goodsid=memberCommentManager.get(commentid).getGoods_id();
        CommentLike commentLike1=commentLikeManager.getByUseridAndCommentId(userid,commentid,goodsid);
        if (commentLike1==null){
            CommentLike commentLike=new CommentLike();
            commentLike.setComment_id(commentid);
            commentLike.setUser_id(userid);
            commentLike.setGoods_id(goodsid);
            commentLike.setLiketime(new Date().getTime());
            commentLike.setStatus(1);//status 1点赞   2取消点赞
            int i=commentLikeManager.create(commentLike);
            if (i==1){
                return JsonResultUtil.getObjectMessageJson(i,"点赞成功");
            }else {
                return JsonResultUtil.getErrorJson("点赞失败");
            }
        }else {
              if (commentLike1.getStatus()==1){// 1:点赞  2:取消点赞
                  commentLikeManager.updateStatus(userid,commentid,2);
                  return JsonResultUtil.getSuccessJson("取消点赞成功");
              }else {
                  commentLikeManager.updateStatus(userid,commentid,1);
                  return JsonResultUtil.getSuccessJson("点赞成功");
              }

        }
    }

    /**
     * //给评论再评论
     * @param userid
     * @param commentid
     * @param commentagain
     * @return
     */
    @ResponseBody
    @RequestMapping("/commentAgain")
    public JsonResult commentAgain(Integer userid,Integer commentid,String commentagain){
        CommentAgain commentAgain1=new CommentAgain();
        Integer goodsid=memberCommentManager.get(commentid).getGoods_id();
        commentAgain1.setComment_id(commentid);
        commentAgain1.setUser_id(userid);
        commentAgain1.setGoods_id(goodsid);
        commentAgain1.setAgaintime(new Date().getTime());
        commentAgain1.setCommentagain(commentagain);
        int i=commentAgainManager.create(commentAgain1);
        if (i==1){
            return JsonResultUtil.getObjectMessageJson(i,"再评论成功 ");
        }else {
            return JsonResultUtil.getErrorJson("再评论失败");
        }
    }


    /**
     *   //删除在评论
     * @param commentagainid
     * @return
     */
    @ResponseBody
    @RequestMapping("/deleteagain")
    public JsonResult deleteCommentAgain(Integer commentagainid){
       int i= commentAgainManager.delete(commentagainid);
       if (i==1){
           return JsonResultUtil.getSuccessJson("删除在评论成功");
       }else {
           return JsonResultUtil.getErrorJson("删除在评论失败");
       }
    }


    /**
     *  //再评论列表
     * @param userid
     * @param commentid
     * @return
     */
    @ResponseBody
    @RequestMapping("/commentagainlist")
    public JsonResult getCommentAgainList(int userid,int commentid){
        List<CommentAgain>  commentAgains=commentAgainManager.getAll(commentid);
        if (commentAgains==null){
            List list=new ArrayList();
            Map map=new HashMap();
            map.put("commentagainid",null);
            map.put("uname",null);
            map.put("commentagain",null);
            list.add(map);
            return JsonResultUtil.getObjectMessageJson(list,"这条评论还没有再评论");
        }
        List list=new ArrayList();
        for (CommentAgain commentAgain:commentAgains){
            Map map=new HashMap();
            map.put("commentagainid",commentAgain.getComment_again_id());
            int userid1=commentAgain.getUser_id();
            String username=memberManager.get(userid1).getUname();
            map.put("uname",username);
            map.put("commentagain",commentAgain.getCommentagain());
            if (userid==userid1){
                map.put("candelete",true);
            }else {
                map.put("candelete",false);
            }
            list.add(map);
        }
        return JsonResultUtil.getObjectMessageJson(list,"再评论列表");
    }




    private String getTimePath(){
        Calendar now = Calendar.getInstance();
        int year=now.get(Calendar.YEAR);
        int month=now.get(Calendar.MONTH) + 1;
        int date=now.get(Calendar.DAY_OF_MONTH);
        int minute=now.get(Calendar.HOUR_OF_DAY);
        String filePath="";
        if(year!=0){
            filePath+=year+"/";;
        }
        if(month!=0){
            filePath+=month+"/";;
        }
        if(date!=0){
            filePath+=date+"/";;
        }
        if(minute!=0){
            filePath+=minute+"/";;
        }
        return  filePath;
    }
}
